package com.bupt.cad.controller;


import com.bupt.cad.common.ApiResult;
import com.bupt.cad.constant.LoginConstant;
import com.bupt.cad.dto.LoginDTO;
import com.bupt.cad.service.impl.ShiroService;
import com.bupt.cad.utils.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 大誌
 * @Date 2019/3/30 22:04
 * @Version 1.0
 */
@RestController
public class ShiroController {

    private final ShiroService shiroService;

    public ShiroController(ShiroService shiroService) {
        this.shiroService = shiroService;
    }


    /**
     * 登录
     */

    @ApiOperation(value = "登陆", notes = "参数:用户名 密码")
    @PostMapping("/sys/login")
    public ApiResult login(HttpServletRequest request, @RequestBody @Validated LoginDTO loginDTO, BindingResult bindingResult) {
        System.out.println(loginDTO.getPassword()+loginDTO.getUsername());
        Map<String, Object> result = new HashMap<>();

        if (bindingResult.hasErrors()) {
            result.put("status", 400);
            result.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(result,"login failed");
        }
        //首先进行验证码验证
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String code = (String) session.getAttribute("validateCode");
        System.out.println("验证码:"+code);
        System.out.println(request.getParameter("validateCode"));
        String submitCode = WebUtils.getCleanParam(request, "validateCode");
        if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,submitCode.toLowerCase())) {
            result.put("LOGIN_ERROR_CODE",LoginConstant.LOGIN_ERROR_CODE_100000);
            result.put("LOGIN_ERROR_MESSAGE", LoginConstant.LOGIN_ERROR_MESSAGE_VALIDATECODE);
            return ResultUtil.error(result,"login failed");
        }
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(token);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
//            session.setAttribute("user",user);
            token.setRememberMe(true);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"账号或密码错误！");
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return ResultUtil.error(-2,"没有权限");
        }
        return ResultUtil.success("login successfully");
//        //用户信息
//        User user = shiroService.findByUsername(username);
//        //账号不存在、密码错误
//        if (user == null || !user.getPassword().equals(password)) {
//            result.put("status", 400);
//            result.put("msg", "账号或密码有误");
//            return ResultUtil.error(result,"login failed");
//        } else {
//            //生成token，并保存到数据库
//            session.setAttribute("user",user);
//            result = shiroService.createToken(user.getUserId());
//            result.put("status", 200);
//            result.put("msg", "登陆成功");
//            return ResultUtil.success(result,"login successfully");
//        }


    }

    /**
     * 退出
     */
    @ApiOperation(value = "登出", notes = "参数:token")
    @PostMapping("/sys/logout")
    //public ApiResult logout(@RequestHeader("token")String token) {
    public ApiResult logout() {
        Map<String, Object> result = new HashMap<>();
//        shiroService.logout(token);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        result.put("status", 200);
        result.put("msg", "您已安全退出系统");
        return ResultUtil.success(result,"exit successfully");
    }

    @PostMapping("/sys/register")
    public ApiResult register(HttpServletRequest request, @RequestBody @Validated LoginDTO loginDTO, BindingResult bindingResult){
        System.out.println(loginDTO.getPassword()+loginDTO.getUsername());
        Map<String, Object> result = new HashMap<>();

        if (bindingResult.hasErrors()) {
            result.put("status", 400);
            result.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(result,"register failed");
        }
//        //首先进行验证码验证
//        Session session = SecurityUtils.getSubject().getSession();
//        String code = (String) session.getAttribute("validateCode");
//        System.out.println("验证码:"+code);
//        System.out.println(request.getParameter("validateCode"));
//        String submitCode = WebUtils.getCleanParam(request, "validateCode");
//        if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,submitCode.toLowerCase())) {
//            result.put("LOGIN_ERROR_CODE",LoginConstant.LOGIN_ERROR_CODE_100000);
//            result.put("LOGIN_ERROR_MESSAGE", LoginConstant.LOGIN_ERROR_MESSAGE_VALIDATECODE);
//            return ResultUtil.error(result,"register failed");
//        }
        if(shiroService.register(loginDTO)){
            return ResultUtil.success(0,"register successfully");
        }else {
            return ResultUtil.error("-1","register failed");
        }
    }
}